package com.yueke.gemini.utils;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring 工具类
 * 用于获取 Spring Bean
 * Created by admin on 2017/5/26.
 */
public final class SpringUtil {
    //spring的配置文件
    private static final String configPath = "classpath*:spring*.xml";
    //定义appicationContext对象
    private static ClassPathXmlApplicationContext ctx = null;// = new ClassPathXmlApplicationContext(configPath); //

    private static void getCpac(){
        synchronized (SpringUtil.class) {
            System.out.println("com.bizvane.ishop.utils.SpringUtil:getCpac:");
            if (ctx == null) {
                System.out.println("com.bizvane.ishop.utils.SpringUtil:getCpac: null");
                ctx = new ClassPathXmlApplicationContext(configPath);
                ctx.registerShutdownHook();

                System.out.println("com.bizvane.ishop.utils.SpringUtil:getCpac: hashcode:"+ctx.hashCode());
            }
        }
    }

    public static <T> T getBean(Class<T> beanCls) {
        System.out.println("com.bizvane.ishop.utils.SpringUtil:getBean<T>:"+beanCls.getName());
        if (ctx == null) {
            System.out.println("com.bizvane.ishop.utils.SpringUtil null:getBean<T>:"+beanCls.getName());
            getCpac();
            //ctx = new ClassPathXmlApplicationContext(configPath);
            //ctx.registerShutdownHook();
        }

        return ctx.getBean(beanCls);
        /*
        String className=beanCls.getName().substring(beanCls.getName().lastIndexOf(".")+1);
        className=className.substring(0, 1).toLowerCase() + className.substring(1);
        return getBean(className);
        */
    }

    public static ClassPathXmlApplicationContext getCtx(){
        System.out.println("com.bizvane.ishop.utils.SpringUtil:getCtx");
        if (ctx == null) {
            System.out.println("com.bizvane.ishop.utils.SpringUtil:getCtx: null");
            getCpac();
            //ctx = new ClassPathXmlApplicationContext(configPath);
            //ctx.registerShutdownHook();
        }
        return ctx;
    }

    public static <T> T getBean(String beanName) {
        System.out.println("com.bizvane.ishop.utils.SpringUtil:getBean："+beanName);
        if (ctx == null) {
            System.out.println("com.bizvane.ishop.utils.SpringUtil:getBean null："+beanName);
            getCpac();
            //ctx = new ClassPathXmlApplicationContext(configPath);
            //ctx.registerShutdownHook();
        }
        return (T) ctx.getBean(beanName);
    }

    public static synchronized void shutdown() {
        if (ctx != null) {
            ctx.close();
            ctx = null;
        }
    }


}
